const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const bcrypt = require('bcrypt');
const config = require('config');
const jwt = require('jsonwebtoken');
const constant = require('../data/constant');


// 注册
router.post('/register',(req,res) => {
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 先确认该用户名是否存在
            connection.query('SELECT username FROM `user` where username="'+req.body.username+'";',async (err,data) => {
                if(err){
                    console.log(err);
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                    connection.end();
                }else{
                    if(data.length>0){
                        res.send({
                            'res':{
                                'ok': 0,
                                'msg':'用户名已经存在'
                            }
                        });
                        connection.end();
                    }else{
                        // 哈希密码
                        const salt = await bcrypt.genSalt(10);
                        let password = await bcrypt.hash(req.body.password,salt);
                        // 然后进行注册操作
                        let  addSql = 'INSERT INTO user(username,password) VALUES(?,?)';
                        var  addSqlParams = [req.body.username,password];

                        connection.query(addSql,addSqlParams,(err,data) => {
                            if(err){
                                console.log(err);
                                res.send({
                                    'res':{
                                        'ok': 0,
                                        'msg':'数据库连接失败'
                                    }
                                });
                            }else{
                                res.send({
                                    'res':{
                                        'ok': 1,
                                        'msg':'注册成功！'
                                    }
                                });
                            }
                            connection.release();
                        });
                    }
                }
            });
        }
    })
})

router.post('/login', (req,res) => {
    console.log("正在登录");
    var Pool = mysql.createPool({
        'host':constant.DB_HOST_NAME,
        'user':constant.DB_USER,
        'password':constant.DB_PWD,
        'database':constant.DB_NAME
    });
    Pool.getConnection( (err,connection) => {
        if(err){
            console.log(err);
            res.send({
                'res':{
                    'ok': 0,
                    'msg':'数据库连接失败'
                }
            });
        }else{
            // 从数据库中查找该用户
            connection.query('SELECT * FROM `user` where username="'+req.body.loginInfo.username+'";',async (err,data) => {
                if(err){
                    console.log(err);
                    res.statusCode = 500;
                    res.send({
                        'res':{
                            'ok': 0,
                            'msg':'数据库连接失败'
                        }
                    });
                }else{
                    data = JSON.stringify(data);//把data对象转为字符串，去掉RowDataPacket
                    data = JSON.parse(data);//把results字符串转为json对象
                    loginType = parseInt(req.body.type);// loginType === 0为学生教师企业用户
                    if(data.length>0 ){
                        // 验证密码
                        //console.log(data[0].password);
                        if(data[0].role<=2){
                            type = 0;
                        }else{
                            type = data[0].role;
                        }
                        const validPassword = await bcrypt.compare(req.body.loginInfo.password,data[0].password);
                        if(type === loginType && data[0].status === 1 && validPassword){
                            const token = jwt.sign({uid:data[0].uid,username:data[0].username},"mySecureKey");
                            res.send({
                                'res':{
                                    'ok': 1,
                                    'msg':'登录成功!',
                                    'token':token,
                                    'username':data[0].username,
                                    'uid':data[0].uid,
                                    'type':type,
                                    'role':data[0].role
                                }
                            });
                        }else if(type !== loginType){
                            res.send({
                                'res':{
                                    'ok': 0,
                                    'msg':'登录失败，您的账号类型选择有误！'
                                }
                            });
                        }else if(data[0].status !== 1){
                            res.send({
                                'res':{
                                    'ok': 0,
                                    'msg':'您的账号被禁用，请联系管理员！'
                                }
                            });
                        }else{
                            console.log('密码错误');
                            res.send({
                                'res':{
                                    'ok': 0,
                                    'msg':'登录失败，用户名或密码错误！'
                                }
                            });
                        } 
                    }else{
                        console.log('密码错误');
                        res.send({
                            'res':{
                                'ok': 0,
                                'msg':'登录失败，用户名或密码错误！'
                            }
                        });
                    }
                }
            });
            connection.release();
        }
    })
});

module.exports = router;